from django.shortcuts import render
from django.http import HttpResponse
from . models import *
import os,time

###用户操作视图

#上传图片专用
def pic_upload(request):
	#判断用户是否上传文件
    myfile = request.FILES.get('head_img',None)
    if not myfile:
        return 'default.jpg'

    #执行上传处理
    filename = str(round(time.time()))+'.'+myfile.name.split('.').pop()

    #打开文件
    destination = open("./static/dash/pics/"+filename,"wb+")
    for chunk in myfile.chunks():      #分块写入文件  
       destination.write(chunk)  
    #关闭文件
    destination.close()
    return filename

#dash首页
def index(request):
	return render(request,'dash/index.html')

#获取dash添加用户页面
def add_user_page(request):
	return render(request,'dash/user/add_page.html')

#添加用户信息
def add_user(request):
	#引入加密模块
	from django.contrib.auth.hashers import make_password,check_password

	try:
		#实例一个user对象 并存入属性
		user = Users()
		user.username = request.POST['username']
		user.pwd = make_password(request.POST['pwd'],None,'pbkdf2_sha256')
		user.gender = request.POST['gender']
		user.address = request.POST['address']
		user.code = request.POST['code']
		user.phone = request.POST['phone']
		user.state = request.POST['state']
		user.head_img = pic_upload(request)
		user.save()
		#跳转到index路由
		return HttpResponse('<script>alert("新增成功");location.href="/dashboard/user/user_list_page"</script>')
	except :
		return HttpResponse('<script>alert("新增失败");location.href="/dashboard/user/user_list_page"</script>')

#获取dash用户列表界面
def user_list_page(request,p_index=1):
	#查询所有用户信息
	user_info = Users.objects.filter()

	#多条件筛选判断
	if request.GET.get('search_type') == 'username':
		user_info = Users.objects.filter(username__contains = request.GET.get('keywords'))
	elif request.GET.get('search_type') == 'phone':
		user_info = Users.objects.filter(phone__contains = request.GET.get('keywords'))
	elif request.GET.get('search_type') == 'gender':
		if request.GET.get('keywords') == '男':
			user_info = Users.objects.filter(gender = 1)
		elif request.GET.get('keywords') == '女':
			user_info = Users.objects.filter(gender = 0)

	#手动封装条件查询内容至flag
	flag = {'search_type':request.GET.get('search_type',''),'keywords':request.GET.get('keywords','')}
	#将flag拼接成字符串keep_search_str返回给模板
	keep_search_str = ''
	for k,v in flag.items():
		keep_search_str += k+'='+v+'&'

	#获取分页数据
	from django.core.paginator import Paginator
	p_index = int(p_index)
	#进行数据分页，实例化对象，设置每页返回数据的条数
	p = Paginator(user_info,5)
	#获取分页后的数据
	user_info = p.page(p_index)
	
	re_info = {'user_info':user_info,'keep_search':keep_search_str}

	return render(request,'dash/user/list_page.html',re_info)

#获取dash编辑用户信息页面
def user_edit_page(request):
	#根据get过来的数据得到单条数据
	re_info ={'user_info':Users.objects.get(id=request.GET['uid'])} 

	return render(request,'dash/user/edit_page.html',re_info)

#更新修改用户信息
def edit_user(request):
    
    try:
    	#根据用户id获取用户对象
	    user = Users.objects.get(id=request.POST['uid'])

	    user.username = request.POST['username']
	    user.phone = request.POST['phone']
	    user.sex = request.POST['gender']
	    user.address = request.POST['address']
	    user.code = request.POST['code']
	    user.state = request.POST['state']
	    #判断是否有头像上传
	    myfile = request.FILES.get("head_img",None)

	    if myfile:
	        #判断是否为默认头像
	        if user.head_img != 'default.jpg':
	            #把原来的用户头像删除
	        	os.remove('./static/dash/pics/'+user.head_img)
	        #上传则获取新的头像
	        user.head_img = pic_upload(request)

	    user.save()
	    return HttpResponse('<script>alert("修改成功");location.href="/dashboard/user/user_list_page"</script>')
    except:
	    return HttpResponse('<script>alert("修改失败");location.href="/dashboard/user/user_list_page"</script>')
    	
#删除用户信息
def del_user(request):
	try:
		#根据用户id获取用户对象
	    user = Users.objects.get(id=request.GET['uid'])
	    #判断是否是默认头像
	    if user.head_img != 'default.jpg':
	    	#把原来的用户头像删除
	    	os.remove('./static/dash/pics/'+user.head_img)

	    user.delete()
	    return HttpResponse('<script>alert("删除成功");location.href="/dashboard/user/user_list_page"</script>')
	except:
	    return HttpResponse('<script>alert("删除失败");location.href="/dashboard/user/user_list_page"</script>')






		



	













